package cn.xinfei.xdecision.util;

import cn.xinfei.xdecision.nacos.NacosSwitchProperties;
import com.dianping.cat.Cat;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.math.RoundingMode;

@Slf4j
public class DataValueCastUtils {
    /**
     * integer(1),string(2),boolean(3),double(4)
     *
     * @param value
     * @param valueType
     * @return
     */
    public static Object cast(String key, Object value, Integer valueType) {
        try {

            if (NacosSwitchProperties.getNacosSwitchProperties().isDebugLog()) {
                log.info("key={},value={},type={}", key, value, valueType);
            }
            if (valueType == 1) {
                //把int转double是为了兼容
//                return cast2Double(value);
                return cast2Integer(value);
            }
            if (valueType == 2) {
                return cast2String(value);
            }
            if (valueType == 3) {
                return cast2Boolean(value);
            }
            if (valueType == 4) {
                return cast2Double(value);
            }
            log.error("未识别的类型，key={},value={},type={}", key, value, valueType);
        } catch (Exception e) {
            log.error("类型转换失败，key={},value={},targetValueTye={},failMsg={}", key, value, valueType, e.getMessage());
            Cat.logError(e);
        }


        return null;
    }

    public static Boolean cast2Boolean(Object value) {
        if (value != null && value.toString().equals("") == false) {
            String s = value.toString();
            if (s.equalsIgnoreCase("false") || s.equalsIgnoreCase("0")) {
                return false;
            }
            if (s.equalsIgnoreCase("true") || s.equalsIgnoreCase("1")) {
                return true;
            }
        }
        return null;
    }

    public static BigDecimal cast2Double(Object value) {
        if (value != null && !value.toString().equals("")) {
            try {
                BigDecimal bigDecimal = new BigDecimal(value.toString());
                return bigDecimal.scale() > 20 ? bigDecimal.setScale(20, RoundingMode.HALF_UP) : bigDecimal;
            } catch (Exception e) {
                log.error("cast2Double value={},error={}", value, e.getMessage(), e);
            }
        }
        return null;
    }

    public static Integer cast2Integer(Object value) {
        if (value != null && value.toString().equals("") == false) {
            return Integer.valueOf(value.toString());
        }
        return null;
    }

    public static String cast2String(Object value) {
        if (value != null) {
            if (!"".equals(value) && !"'".equals(value) && value.toString().startsWith("'") && value.toString().endsWith("'")) {
                return value.toString().substring(1, value.toString().length() - 1);
            }
            return value.toString();
        }
        return null;
    }
}
